package com.whately.core.base.logbackcfg;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.rolling.RollingFileAppender;
import com.whately.core.base.exception.ServiceException;
import com.whately.core.base.utils.HumpTools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ConcurrentHashMap;


@Component
@Slf4j
public class WhatelyLoggerBuilder{
    private ConcurrentHashMap<String, Logger> container = new ConcurrentHashMap<>();

    @PostConstruct
    public void init(){
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

        // /rcrlogs/jnybes 或者 .
        String log_path = context.getProperty("logPath");
        if(StringUtils.isBlank(log_path)){
            throw new ServiceException(400,"log path 未定义，请指定scope=\"context\" ");
        }
        if(log_path.endsWith("/")){
            throw new ServiceException(400,"log path 请不要以/结尾 ，log path = "+log_path);
        }

        log.info("log_path is {} ",log_path);
    }



    public Logger fetchLogger(Class<?> clazz) {
        String mapKey = clazz.getName();

        Logger logger = container.get(mapKey);
        if (logger != null) {
            return logger;
        }
        //超过一定数量，就不再创建了
        if(container.size()>100){
            return (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(clazz);
        }
        synchronized (WhatelyLoggerBuilder.class) {
            logger = container.get(mapKey);
            if (logger != null) {
                return logger;
            }
            logger = build(clazz);
            container.put(mapKey, logger);
        }
        return logger;
    }




    private  Logger build(Class<?> clazz) {
        String fileName = HumpTools.humpToLine(clazz.getSimpleName(), HumpTools.SeparatorEnum.mid_line);

        RollingFileAppender infoAppender = new WhatelyAppenderFactory().createRollingFileAppender(fileName, Level.INFO);
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger logger = context.getLogger(clazz.getName()+"(-inner)");
        //设置不向上级打印信息
        logger.setAdditive(false);
        logger.addAppender(infoAppender);

        return logger;
    }

}
